<?php

namespace Module\Cms;

use Manager\User as Manager;
use W3\Exception;

!defined('W3_ROOT_DIR') AND exit;

/**
 * 登录组件
 *
 * @author edikud
 * @date 2022/10/22
 * @copyright Copyright (c) 2022 W3 (http://www.mcooo.com)
 * @license GNU General Public License 2.0
 */
class Login extends Manager
{
    /**
     * 初始化
     *
     * @access protected
     * @return void
     */
    protected function init()
    {
		# 定义变量默认数据
		$this->parameter([

			# 设置主体
			'main' => 'login',
			
			# 主题目录
			'themeDir' => file_exists($this->themeFile('login.php')) 
			    ? $this->themeFile()
				: W3_ROOT_DIR . 'system/static/html/',
			
			# 主题文件
			'themeFile' => 'login',
			
			# 默认title
			'title' => __('登录'),
			
	    ], true);
		
        /** 如果已经登录 */
        if ($this->auth->hasLogin()) {

            /** 直接跳转 */
            $this->redirect($this->adminUrl(false));
        }
	}

    /**
     * 执行函数
     *
     * @access public
     * @return void
     */
    public function execute()
    {		
		/** 输出内容 */
		$this->request->isGet() 
		    && $this->layout->set($this->loginForm());
	
		$this->on($this->request->isPost())->action();
    }

    /**
     * 初始化函数
     *
     * @access public
     * @return void
     */
    public function action()
    {
		/** 验证格式 */
        if ($this->loginForm()->validate()) {
			$this->goBack();
        }

        /** 开始验证用户 **/
        $valid = $this->auth->login($this->request->name, $this->request->password,
            false, 1 == $this->request->remember ? $this->config->time + $this->config->timezone + 30*24*3600 : 0);

        /** 比对密码 */
        if (!$valid) {
			
            /** 防止穷举,休眠3秒 */
            //sleep(3);

            $this->notice(__('用户名或密码无效'), 'notice');
			
            $this->goBack('?referer=' . urlencode($this->request->referer));
        }

        /** 跳转验证后地址 */
        if (!empty($this->request->referer)) {
            /** fix #952 & validate redirect url */
            if (
                0 === strpos($this->request->referer, $this->adminUrl(false))
                || 0 === strpos($this->request->referer, $this->siteUrl(false))
            ) {
                $this->redirect($this->request->referer);
            }
        } elseif (!$this->auth->check('contributor', true)) {
            /** 不允许普通用户直接跳转后台 */
            $this->redirect($this->adminUrl('profile', false));
        }

        $this->redirect($this->adminUrl(false));
    }

}
